package com.kfm.servlet;

import com.kfm.model.FileDO;
import com.kfm.model.FileDTO;
import com.kfm.service.FileService;
import com.kfm.util.LoginUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/files")
public class FilesServlet extends HttpServlet {

    private FileService service = new FileService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        if (LoginUtil.isNonLogin(req.getSession())){
            response.sendRedirect("login");
            return;
        }

        response.setContentType("text/html;charset=utf-8");

        List<FileDTO> fileDTOS = service.queryAllWithAccount();

        StringBuffer sb = new StringBuffer();

        sb.append("""
                <h1 style="text-align:center;">文件列表</h1>
                <table width="800px" border="1" cellspacing="0">
                    <tr>
                        <th>编号</th>
                        <th>文件名</th>
                        <th>访问路径</th>
                        <th>大小</th>
                        <th>创建者</th>
                    </tr>
                """);
        if (fileDTOS.size() == 0){
            sb.append("""
                    <tr style="text-align:center;">
                        <td colspan="4"> 没有数据 </td>
                    </tr>
                    """);
        } else{
            for (int i = 0; i < fileDTOS.size(); i ++){
                int num = i +1;
                FileDTO fileDO = fileDTOS.get(i);


                sb.append("""
                    <tr>
                        <td>%s</td>
                        <td>%s</td>
                        <td><a href="%s" target="_blank">预览</a></td>
                        <td>%s KB</td>
                        <td>%s</td>
                    </tr>
                    """.formatted(num, fileDO.getName(), fileDO.getUrl(), fileDO.getSize() / 1024, fileDO.getUsername()));
            }
        }

        sb.append("</table>");

        PrintWriter writer = response.getWriter();


        writer.write(sb.toString());

    }
}
